using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;

/// <summary>
/// UI管理器，负责处理全局UI设置和优化
/// 应该在每个场景中都存在一个实例
/// </summary>
public class UIManager : MonoBehaviour
{
    [Header("UI设置")]
    [SerializeField] private bool autoScaleUI = true;
    [SerializeField] private bool optimizeForMobile = true;
    
    [Header("字体大小")]
    [SerializeField] private bool adjustFontSize = true;
    [SerializeField] private float mobileFontScale = 1.3f; // 手机上字体放大倍数
    
    [Header("移动设备优化")]
    [SerializeField] private float mobileUIScale = 1.5f; // 移动设备UI缩放倍数
    [SerializeField] private float mobileButtonScale = 1.2f; // 移动设备按钮缩放倍数
    [SerializeField] private float mobileKeyboardScale = 1.5f; // 虚拟键盘按钮缩放倍数
    
    private void Awake()
    {
        Debug.Log($"[UIManager] 初始化，当前场景: {SceneManager.GetActiveScene().name}, 屏幕: {Screen.width}x{Screen.height}");
    }
    
    private void Start()
    {
        StartCoroutine(SetupUI());
    }
    
    /// <summary>
    /// 配置场景中的所有UI元素
    /// </summary>
    private IEnumerator SetupUI()
    {
        // 等待一帧确保所有UI组件已经初始化
        yield return null;
        
        // 处理Canvas缩放
        if (autoScaleUI)
        {
            SetupCanvasScalers();
        }
        
        // 处理字体大小
        if (adjustFontSize && IsMobileDevice())
        {
            AdjustFontSizes();
        }
        
        // 如果是移动设备，优化UI大小
        if (optimizeForMobile && IsMobileDevice())
        {
            AdaptUIForMobileDevices();
        }
        
        // 确保WordDatabase存在
        EnsureWordDatabaseExists();
        
        Debug.Log("[UIManager] UI设置完成");
    }
    
    /// <summary>
    /// 设置所有Canvas的缩放
    /// </summary>
    private void SetupCanvasScalers()
    {
        Canvas[] allCanvases = FindObjectsOfType<Canvas>();
        Debug.Log($"[UIManager] 找到 {allCanvases.Length} 个Canvas");
        
        foreach (Canvas canvas in allCanvases)
        {
            if (canvas.renderMode == RenderMode.ScreenSpaceOverlay || 
                canvas.renderMode == RenderMode.ScreenSpaceCamera)
            {
                // 检查是否已有UIScaler
                UIScaler scaler = canvas.GetComponent<UIScaler>();
                if (scaler == null)
                {
                    // 添加UIScaler组件
                    scaler = canvas.gameObject.AddComponent<UIScaler>();
                    Debug.Log($"[UIManager] 为Canvas '{canvas.name}' 添加UIScaler组件");
                }
                
                // 为移动设备优化
                if (optimizeForMobile && IsMobileDevice())
                {
                    scaler.OptimizeForDeviceOrientation();
                }
                else
                {
                    scaler.ApplyScaling();
                }
            }
        }
    }
    
    /// <summary>
    /// 调整所有文本的字体大小
    /// </summary>
    private void AdjustFontSizes()
    {
        Text[] allTexts = FindObjectsOfType<Text>();
        Debug.Log($"[UIManager] 调整 {allTexts.Length} 个文本的字体大小");
        
        foreach (Text text in allTexts)
        {
            // 保存原始字体大小
            int originalSize = text.fontSize;
            
            // 计算新字体大小
            int newSize = Mathf.RoundToInt(originalSize * mobileFontScale);
            
            // 应用新字体大小
            text.fontSize = newSize;
            
            Debug.Log($"[UIManager] 文本 '{text.name}' 字体大小从 {originalSize} 调整为 {newSize}");
        }
    }
    
    /// <summary>
    /// 确保WordDatabase存在
    /// </summary>
    private void EnsureWordDatabaseExists()
    {
        if (WordDatabase.Instance == null)
        {
            Debug.LogWarning("[UIManager] 未找到WordDatabase实例，创建一个新实例");
            GameObject wordDBObject = new GameObject("WordDatabase");
            wordDBObject.AddComponent<WordDatabase>();
            DontDestroyOnLoad(wordDBObject);
        }
        else
        {
            Debug.Log("[UIManager] WordDatabase实例已存在");
        }
    }
    
    /// <summary>
    /// 检测是否为移动设备
    /// </summary>
    private bool IsMobileDevice()
    {
        return Application.isMobilePlatform || 
               SystemInfo.deviceType == DeviceType.Handheld ||
               Screen.width < 800; // 简易检测
    }
    
    /// <summary>
    /// 在游戏中动态调整UI缩放
    /// </summary>
    public void AdjustUIScaling(float matchValue)
    {
        UIScaler[] scalers = FindObjectsOfType<UIScaler>();
        foreach (UIScaler scaler in scalers)
        {
            scaler.AdjustScaling(matchValue);
        }
    }
    
    /// <summary>
    /// 为移动设备优化UI元素大小和可点击性
    /// </summary>
    public void AdaptUIForMobileDevices()
    {
        Debug.Log("[UIManager] 为移动设备优化UI元素大小...");
        
        // 增加UI元素的缩放比例
        Canvas[] allCanvases = FindObjectsOfType<Canvas>();
        foreach (Canvas canvas in allCanvases)
        {
            if (canvas.renderMode == RenderMode.ScreenSpaceOverlay || 
                canvas.renderMode == RenderMode.ScreenSpaceCamera)
            {
                CanvasScaler scaler = canvas.GetComponent<CanvasScaler>();
                if (scaler != null)
                {
                    // 增加缩放系数
                    float currentScale = scaler.scaleFactor;
                    scaler.scaleFactor = currentScale * mobileUIScale;
                    Debug.Log($"[UIManager] Canvas '{canvas.name}' 缩放从 {currentScale} 调整为 {scaler.scaleFactor}");
                }
            }
        }
        
        // 增大所有按钮的点击区域
        Button[] allButtons = FindObjectsOfType<Button>();
        foreach (Button button in allButtons)
        {
            RectTransform rectTransform = button.GetComponent<RectTransform>();
            if (rectTransform != null)
            {
                // 保存原始尺寸
                Vector2 originalSize = rectTransform.sizeDelta;
                
                // 检查是否是键盘按钮
                bool isKeyboardButton = IsKeyboardButton(button);
                float scaleMultiplier = isKeyboardButton ? mobileKeyboardScale : mobileButtonScale;
                
                // 增大按钮尺寸
                rectTransform.sizeDelta = originalSize * scaleMultiplier;
                Debug.Log($"[UIManager] 按钮 '{button.name}' 尺寸从 {originalSize} 调整为 {rectTransform.sizeDelta}");
            }
        }
        
        // 调整输入字段大小
        InputField[] allInputFields = FindObjectsOfType<InputField>();
        foreach (InputField inputField in allInputFields)
        {
            RectTransform rectTransform = inputField.GetComponent<RectTransform>();
            if (rectTransform != null)
            {
                // 保存原始尺寸
                Vector2 originalSize = rectTransform.sizeDelta;
                
                // 增大输入字段尺寸
                rectTransform.sizeDelta = originalSize * mobileButtonScale;
                Debug.Log($"[UIManager] 输入字段 '{inputField.name}' 尺寸从 {originalSize} 调整为 {rectTransform.sizeDelta}");
            }
        }
    }
    
    /// <summary>
    /// 检查是否是键盘按钮(虚拟按键)
    /// </summary>
    private bool IsKeyboardButton(Button button)
    {
        // 检查按钮名称是否包含常见键盘按钮标识
        string buttonName = button.name.ToLower();
        string buttonText = "";
        
        // 获取按钮的文本
        Text buttonTextField = button.GetComponentInChildren<Text>();
        if (buttonTextField != null)
        {
            buttonText = buttonTextField.text.ToLower();
        }
        
        // 检查是否是虚拟键盘按钮
        bool isKeyboardButton = buttonName.Contains("key") || 
                              buttonName.Contains("letter") || 
                              buttonName.Contains("keyboard") ||
                              (buttonText.Length == 1 && char.IsLetter(buttonText[0])) ||
                              buttonText == "delete" || 
                              buttonText == "enter" || 
                              buttonText == "backspace";
        
        return isKeyboardButton;
    }
} 